/*---------------------------------------------------------------------------
 * Speculoos, LDAP to objet mapping.
 * Copyright (C) 2006  Norsys and OQube
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 * 
 * Created on Oct 19, 2005
 * --------------------------------------------------------------------------*/
package speculoos.commons.mockldap;

import java.io.StringReader;

import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;

public abstract class Filter {


    /**
     * Parse expression to make filter.
     * <p>
     * <strong>This implementation is uncomplete</strong>
     * Parses a RFC2254 compliant string into a Filter object.
     * At present time, this method only parses <code>AND</code> 
     * operator and equality matching.
     * </p>
     * 
     * @param expr the expression to parse
     * @throws NamingException 
     */
    public static Filter parse(String expr) throws NamingException {
        /* 
         */
    	FilterParser fp = new FilterParser(new StringReader(expr));
    	try {
			return fp.parse();
		} catch (ParseException e) {
			throw new NamingException("Unable to parse expression "+expr+" :"+e.getLocalizedMessage());
		}
    }
    
    /**
     * Checks that given context matches this filter.
     * 
     * @param ctx
     * @return
     * @throws NamingException 
     */
    public abstract boolean match(TestDirContext ctx) throws NamingException;
    

    /**
     * A basic AND filter made from a list of attributes.
     * 
     * @param matchingAttributes
     * @return
     * @throws NamingException 
     */
    public static Filter makeFilter(Attributes matchingAttributes) throws NamingException {
        AndFilter cur = new AndFilter();
        for(NamingEnumeration e = matchingAttributes.getAll();e.hasMore();) {
            Attribute attr = (Attribute)e.next();
            MatchFilter mf = new MatchFilter(attr);
            cur.add(mf);
                
        }
        return cur;
        }
}
